package org.yzh.web.service.impl;
import java.time.LocalDateTime;

import com.github.dozermapper.core.Mapper;
import io.github.yezhihao.netmc.session.Session;
import io.github.yezhihao.netmc.session.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yzh.web.model.entity.BaseDeviceInfo;
import org.yzh.web.model.vo.DeviceInfo;
import org.yzh.web.model.vo.DeviceOnlineInfo;
import org.yzh.web.service.SessionService;

import java.util.Optional;
import java.util.function.Function;

/**
 * @author lsj
 * @date 2021/1/14 11:27
 */
@Service
public class SessionServiceImpl implements SessionService {
    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private Mapper dozerMapper;

    @Override
    public boolean isExistsByDeviceId(String deviceId) {
        return this.getDeviceInfoByDeviceId(deviceId).isPresent();
    }

    @Override
    public boolean isExistsByPlateNo(String plateNo) {
        return this.getDeviceInfoByPlateNo(plateNo).isPresent();
    }

    public Optional<DeviceInfo> getDeviceInfoByDeviceId(String deviceId) {
        if (StringUtils.isEmpty(deviceId)) {
            return Optional.empty();
        }
        return sessionManager.all().stream().filter(s -> {
            DeviceInfo subject = (DeviceInfo)s.getSubject();
            return subject != null && deviceId.equals(subject.getDeviceId());
        }).map(session -> (DeviceInfo)session.getSubject()).findFirst();
    }

    public Optional<DeviceInfo> getDeviceInfoByPlateNo(String plateNo) {
        if (StringUtils.isEmpty(plateNo)) {
            return Optional.empty();
        }
        return sessionManager.all().stream().filter(s -> {
            DeviceInfo subject = (DeviceInfo)s.getSubject();
            return subject != null && plateNo.equals(subject.getPlateNo());
        }).map(session -> (DeviceInfo)session.getSubject()).findFirst();
    }




    @Override
    public void saveDeviceOnlineInfo(Session session, BaseDeviceInfo device) {
        if (device == null || StringUtils.isEmpty(device.getDeviceId())) {
            return;
        }
        /* 拼装上线事件 Key */
        String key = device.getDeviceId() + ":" + device.getPlateNo() + DeviceOnlineInfo.SESSION_KEY;
        DeviceOnlineInfo onlineInfo = dozerMapper.map(device, DeviceOnlineInfo.class);
        onlineInfo.setOnlineTime(session.getCreationTime());
        session.setAttribute(key, onlineInfo);
    }
}
